package com.mec.beans.y2012;

import java.io.File;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;

import org.apache.log4j.Logger;

public class CommonIndexBean {
	
	private HttpServletRequest request;
	
	final String[] VALID_SUFFIX = {".html", ".html", ".jsp"};
	String[] validSuffix;
	String contextPath;
	String requestURI;
	
	//request.attributes.names: 
	final String P_CONTEXT_PATH = "context-path";
	final String P_REQUEST_URI = "request-uri";
	final String P_VALID_SUFFIX = "valid-suffix";
	//String currentDir = null;
	//String currentPath = null;
	
	
	public CommonIndexBean(HttpServletRequest request){
		this.request = request;
		
		initRequestParams();
	}
	
	
	public void initRequestParams(){
		contextPath = (String) request.getAttribute(P_CONTEXT_PATH);
		requestURI = (String) request.getAttribute(P_REQUEST_URI);
		
		
		validSuffix = (String[]) request.getAttribute(P_VALID_SUFFIX);
		if(null == validSuffix || 0 == validSuffix.length){
			validSuffix = VALID_SUFFIX;
		}
		
	}

	public File getCurrentDir(){
		ServletContext app = request.getServletContext();
		String currentPath = getCurrentPath();
		String dirStr = app.getRealPath(currentPath);
		
		
		File dir = new File(dirStr);
		return dir;
	}
	
	public boolean validIndexFile(String fileName){
		boolean retval = false;
		
		String fileNameLC = fileName.toLowerCase();
		for(String v:validSuffix){
			if(fileNameLC.endsWith(v)){
				retval = true;
				break;
			}
		}
		
		
		return retval;
	}
	
	public String getCurrentPath(){
		String retval = null;
		
		String subURI = getSubURI();
		int endIndex = subURI.lastIndexOf("/") + 1;
		
		retval = subURI.substring(0, endIndex); 
		
		return retval;
	}
	
	private String getSubURI(){
		String retval = null;
		
		//String contextPath = request.getContextPath();
		//String requestURI = request.getRequestURI();
		
		retval = requestURI.replaceFirst(contextPath, "");
		
		return retval;
	}
	
	public String getNewestFile(){
		File dir = getCurrentDir();
		File[] files = dir.listFiles();
		
		File newestFile = files[0];
		for(File file : files){
			if (newestFile.lastModified() <file.lastModified()
					&& validIndexFile(file.getName())
					){
				newestFile = file;
			}
		}
		String newestFileName = newestFile.getName();
		
		return newestFileName;
	}

	private static final Logger logger = 
			Logger.getLogger(CommonIndexBean.class);
}
